// handleUpdateItem.js

import handleSave from "./handleSave.js";
import handleQuery from "./handleQuery.js";
import useJournalStore from "@/store/journal.js";

export default function (item) {
  const journalStore = useJournalStore();
  if (!item) {
    return new Promise((resolve, reject) => {
      handleQuery()
        .then((content) => {
          // 内容更新则替换store内容，防止不必要的ui更新
          const contentJson = JSON.stringify(content);
          if (
            journalStore.diversionShareStatus.lastCurrentListJSON != contentJson
          ) {
            journalStore.diversionShareStatus.currentList = content;
            journalStore.diversionShareStatus.currentListFiltered =
              handleFilter(content);
            journalStore.diversionShareStatus.lastCurrentListJSON = contentJson;
          }
          resolve(content);
        })
        .catch((error) => {
          console.log("loadCurrentList", error);
          reject(error);
        });
    });
  } else {
    return new Promise((resolve, reject) => {
      journalStore.diversionShareStatus.isToolboxLoading = true;
      handleSave(item)
        .then(() => {
          handleQuery()
            .then((content) => {
              journalStore.diversionShareStatus.currentList = content;
              journalStore.diversionShareStatus.currentListFiltered =
                handleFilter(content);
              journalStore.diversionShareStatus.lastCurrentListJSON =
                JSON.stringify(content);
              journalStore.diversionShareStatus.isToolboxLoading = false;
              resolve(content);
            })
            .catch((error) => {
              console.error("handleUpdateItem.handleQuery.error", error);
              journalStore.diversionShareStatus.isToolboxLoading = false;
              reject(error);
            });
        })
        .catch((error) => {
          console.error("handleUpdateItem.handleSave.error", error);
          journalStore.diversionShareStatus.isToolboxLoading = false;
          reject(error);
        });
    });
  }
}

const handleFilter = (content) => {
  return content.filter((item) => item.reportPlan == 0 || item.reportFlow == 0);
};
